<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/27 0027
 * Time: 16:49
 */

namespace Api\Service;

use WeChat\Contracts\DataArray;
use WeChat\Contracts\Tools;
use WeChat\Exceptions\InvalidArgumentException;
use WeChat\Exceptions\InvalidResponseException;

class AdDeployService
{
    /**
     * 静态配置
     * @var DataArray
     */
    private static $config;
    //私有属性，用于保存实例
    private static $instance;
    /**
     * 设置及获取参数
     * @param array $option
     * @return array
     */
    public static function config($option = null)
    {
        /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
        }
        if (empty($option)) $option = [
            // 必需参数
            'access_token'       => $config['DEPLOY_ACCESS_TOKEN'],
            'access_secret'      => $config['DEPLOY_ACCESS_SECRET'],
            'gateway'            => $config['DEPLOY_GATEWAY'],
        ];
        if (is_array($option)) {
            self::$config = new DataArray($option);
        }
        if (self::$config instanceof DataArray) {
            return self::$config->get();
        }
        return [];
    }
    public static function instance(array $arguments = [])
    {
        $config = [];
        if (is_array($arguments) && count($arguments) > 0) {
            $option = array_shift($arguments);
            $config = is_array($option) ? $option : self::config();
        }
        return new self(empty($config) ? self::config() : $config);
    }
    /**
     * 构造方法私有化，防止外部创建实例
     * AdDeployService constructor.
     * @param array $arguments
     */
    public function __construct(array $arguments = [])
    {
        if (is_array($arguments) && count($arguments) > 0) {
            $arguments = array_shift($arguments);
        }
        $config = self::config($arguments);
        if (empty($config['access_token'])) {
            throw new InvalidArgumentException("Missing Config -- [access_token]");
        }
        if (empty($config['access_secret'])) {
            throw new InvalidArgumentException("Missing Config -- [access_secret]");
        }
        if (empty($config['gateway'])) {
            throw new InvalidArgumentException("Missing Config -- [gateway]");
        }
        self::$config = new DataArray($config);
    }

    /**
     * 部署广告到设备
     * @param string $itemName 本次发布的名称（请赋有意义的值方便后续查询,建议用订单号吧）
     * @param string $itemIds 需要发布的广告 id 字符串
     * @param string $cMarks 发布的目标设备标识，多个 cMark 以英文逗号隔开
     * @param string $sDate 播放起始日 yyyy-MM-dd 格式
     * @param string $eDate 播放截止日 yyyy-MM-dd 格式
     * @param string $beginTime 开始时间 hh:mm:ss ;24hour 时分秒
     * @param string $endTime 结束时间 hh:mm:ss ;24hour 时分秒
     * @param int $playtimetype 播放模式
     * @param int $playCount 1:普通按序循环播放模式
     * @param int $pType 发布类型，0：追加
     * @return array|bool|string
     * @throws InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public function deploy($itemName = '', $itemIds = '', $cMarks = '', $sDate = '', $eDate = '', $beginTime, $endTime, $playtimetype = 1, $playCount = 10,$pType = 0)
    {
        $config = self::$config->get();
        $timestamp = time();
        $access_secret_md5 = md5($config['access_secret']);
        $sign = md5($config['access_token'] . $access_secret_md5 . $timestamp);

        $result = Tools::post($config['gateway'],Tools::arr2json([
            'access_token' => $config['access_token'],
            'timestamp' => $timestamp,
            'sign' => $sign,
            'cMarks' => $cMarks,
            'itemIds' => $itemIds,
            'itemName' => $itemName,
            'sDate' => $sDate,
            'eDate' => $eDate,
            'beginTime' => $beginTime,
            'endTime' => $endTime,
            'playtimetype' => $playtimetype,
            'playCount' => $playCount,
            'pType' => $pType,
        ]));
        if (is_array($json = json_decode($result, true))) {
            return Tools::json2arr($result);
        }
        return $result;
    }

    /**
     * 新增广告 获取广告ID
     * @param string $scenename
     * @param string $path_url
     * @param int $fileSize
     * @param string $ad_type
     * @return array|bool|string
     * @throws InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public function addItem($scenename = '测试广告',$path_url = '',$fileSize = 0,$ad_type = '1')
    {
        $config = self::$config->get();
        $timestamp = time();
        $access_secret_md5 = md5($config['access_secret']);
        $sign = md5($config['access_token'] . $access_secret_md5 . $timestamp);
        $itemId = '';
        if($ad_type == '1'){
            $itemInfo = [
                'type' => 'img',// img 表示图片类型
                'source' => $path_url,
                'src' => $path_url,
                'name' => '图片一',
                '_long' => 5,
                'mh' => 0,
                'id' => '',
                'fileSize' => $fileSize,//源文件大小
            ];
        } elseif ($ad_type == '2'){
            $itemInfo = [
                [
                    'type' => 'video',
                    'source' => $path_url,
                    'src' => $path_url,
                    'name' => '视频一',
                    '_long' => 35,//视频的时长
                    'mh' => 0,
                    'id' => '',
                    'fileSize' => $fileSize,//源文件大小
                ]
            ];
        } else {
            return false;
        }
        $scene = [
            'elementcount' => 1,//元素数目，用户如果为素材全屏的节目，一般设置为1
            'scenename' => $scenename,
            'scenetime' => 40,//很重要，整个场景播放时间
            'screen_orientation' => 2,
            'width' => 1920,
            'height' => 1080,
            'coverpage' => '',//广告的封面图片，类似缩略图概念，无此值，则默认用元素1的素材1的第一张图缩略图作为广告缩略图
            'datalist' => [
                [
                    'x' => 0,
                    'y' => 0,
                    'width' => 1920,
                    'height' => 1080,
                    'delay' => 5,
                    'curimglist' => [ $itemInfo ]
                ]
            ]
        ];
        $str_scene = json_encode($scene,JSON_UNESCAPED_UNICODE);
        $result = Tools::post($config['gateway'],Tools::arr2json([
            'access_token' => $config['access_token'],
            'timestamp' => $timestamp,
            'sign' => $sign,
            'itemId' => $itemId,
            'scene' => $str_scene
        ]));
        if (is_array($json = json_decode($result, true))) {
            return Tools::json2arr($result);
        }
        return $result;
    }
}